define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var pageIndex = 1;
    var pageSize = 20;
    var firstTime = true;

    var addGoods = {
        init: function () {

            this.checkParam();
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "外店类目管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.getplatform();
            this.initGoodsTable();
            this.initValidator();
            this.bindEvent();
            this.cachedGoodsArray = new Array();
            this.goodsArray = new Array();
        },
        /*
         参数检查
         */
        checkParam: function () {
            var self = this;
            var actcatId = CRM.getUrlParam("actcatId");
            var actcatName = CRM.getUrlParam("actcatName");
            var cityCode = CRM.getUrlParam("cityCode");
            if (!actcatId || !actcatName || !cityCode) {
                CRM.showDialog("重要参数缺失,3s后返回");
                setTimeout(function () {
                    window.location.href = "./category.html";
                }, 3000);
            } else {
                self.actcatId = actcatId;
                self.actcatName = actcatName;
                self.cityCode = cityCode;
                //设置返回按钮的参数
                $('#back').attr("href", "./categoryGoods.html?actcatId=" + actcatId + "&actcatName=" + actcatName + "&cityCode=" + cityCode);
            }
        },
        /*
         获取isp列表
         */
        getplatform: function () {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/ispList"),
                "dataType": "json",
                contentType: "application/json",
                "data": {
                    "time": new Date().getTime()
                },
                "success": function (req) {
                    if (req.status) {
                        var arr = [];
                        $.each(req.entry, function (index, item) {
                            arr.push("<label><input type='checkbox' value='" + item.id + "'>" + item.name + "</label>");
                        });
                        $("#platform").html(arr.join(''));
                    } else {
                        CRM.showDialog(req.message);
                    }
                },
                error: function (e) {
                    //请求出错处理
                    CRM.showDialog("获取平台列表,请求服务异常！");
                }
            });
        },
        /*
         初始化商店信息
         */
        initGoodsTable: function () {
            var self = this;
            self.shopTable = $("#goods_table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": true,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                'bStateSave': true,
                "sAjaxSource": CRM.getOuterUrl('/outway/sync/item/spu/price/page'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    $('#chooseAllBtn').removeAttr("checked");
                    var _url = CRM.getOuterUrl('/itemcenter/crm/spu/search/childrenSpu/page');
                    var dataString = {
                        "barcode": $("#barcode_input").val(),
                        "name": $("#goodsName_input").val(),
                        "pageNo": aoData[3].value / aoData[4].value + 1,
                        "pageSize": aoData[4].value,
                        "timestamp": new Date().getTime()
                    };
                    CRM.request({
                        "type": 'GET',
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = req.entry.totalCount;
                                    resultData.iTotalRecords = req.entry.totalCount;
                                    for (var length in req.entry.list) {
                                        resultData.aaData.push([
                                            req.entry.list[length],
                                            CRM.htmlEncode("[" + req.entry.list[length].brand + "]" + req.entry.list[length].name),
                                            CRM.htmlEncode(req.entry.list[length].property),
                                            CRM.htmlEncode(req.entry.list[length].unit),
                                            req.entry.list[length].barcode,
                                            req.entry.list[length].id
                                        ]);
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        },
                        error: function (e) {
                            //请求出错处理
                            $("#msg_dialog_content").text("获取店铺列表,请求服务异常！");
                            $('#msg_dialog').modal('show');
                        }
                    });
                },
                "aaSorting": [[1, "asc"]],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [
                    {
                        "sTitle": '<input type="checkbox" onclick="chooseAll()" id="chooseAllBtn">',
                        "mRender": function (data) {
                            var flag = 0;
                            for (var i in self.cachedGoodsArray) {
                                if (self.cachedGoodsArray[i].id == data.id) {
                                    flag = 1;
                                    break;
                                }
                            }
                            var html = '<input type="checkbox" data-barcode="' + data.barcode + '" data-name="' + data.name + '" data-id="' + data.id
                                + '" data-brand="' + data.brand + '" data-property="' + data.property + '" data-unit="' + data.unit
                                + '" onChange="cachedGoods(\'' + data.barcode + '\',\'' + data.name + '\',\'' + data.id + '\',\'' + data.brand + '\',\''
                                + data.property + '\',\'' + data.unit + '\')"' + (flag ? 'checked="checked"' : '') + '>';
                            return html;
                        }
                    },
                    {
                        "sTitle": "SPU 名称",
                        "bSortable": true
                    },
                    {
                        "sTitle": "SPU 规格",
                        "bSortable": true
                    },
                    {
                        "sTitle": "SPU 单位",
                        "bSortable": true
                    },
                    {
                        "sTitle": "SPU 条码",
                        "bSortable": true
                    },
                    {
                        "sTitle": "SPU ID",
                        "bSortable": true
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /*
         缓存待增加的商品
         */
        cachedGoods: function (barcode, name, id, brand, property, unit) {
            var self = this;

            var flag = 0;
            for (var i in self.cachedGoodsArray) {
                if (self.cachedGoodsArray[i].id == id) {
                    flag = 1;
                    break;
                }
            }
            if (flag) {
                self.cachedGoodsArray.splice(i, 1);
                $("#choosed_goods_list li[value='" + id + "']").remove();
            } else {
                self.cachedGoodsArray.push({
                    "name": name,
                    "barcode": barcode,
                    "id": id,
                    "brand": brand,
                    "unit": unit,
                    "property": property
                });
                var html = "<li value=\'" + id + "\'>" + "[" + brand + "]" + name + "(" + barcode + ")  ";
                $('#choosed_goods_list').append(html);
            }
            //console.log(self.cachedGoodsArray);
        },
        /*
         全选
         */
        chooseAll: function () {
            if ($('#chooseAllBtn').is(':checked')) {
                $('#goods_table tbody input').prop("checked", true);
            } else {
                $('#goods_table tbody input').removeAttr("checked");
            }
            $('#goods_table tbody input').each(function () {
                self.cachedGoods($(this).attr("data-barcode"), $(this).attr("data-name"), $(this).attr("data-id"), $
                (this).attr("data-brand"), $(this).attr("data-property"), $(this).attr("data-unit"));
            });
        },
        /*
         添加商品
         */
        showCachedGoods: function () {
            var self = this;
            //数组取并集
            for (var i in self.cachedGoodsArray) {
                var flag = 1;
                for (var j in self.goodsArray) {
                    if (self.goodsArray[j].id == self.cachedGoodsArray[i].id) {
                        flag = 0;
                        break;
                    }
                }
                if (flag) {
                    self.goodsArray.push(self.cachedGoodsArray[i]);
                }
            }
            $('#chooseGoods_dialog').modal("hide");
            self.refreshGoodsList();
        },
        /*
         刷新 待添加商品列表
         */
        refreshGoodsList: function () {
            var self = this;
            $('#cached_goods_list tbody').html("");
            for (var i in self.goodsArray) {
                var html = '<tr><td>[' + self.goodsArray[i].brand + ']' + self.goodsArray[i].name + '</td><td>' + self.goodsArray[i].property + '</td><td>'
                    + self.goodsArray[i].unit + '</td><td>' + self.goodsArray[i].barcode + '</td><td>' + self.goodsArray[i].id
                    + '</td><td><button class="btn btn-danger" onclick="deleteCachedGoods(\'' + self.goodsArray[i].id + '\')">删除</button></td></tr>';
                $('#cached_goods_list tbody').append(html);
            }
            //console.log(self.goodsArray);
        },
        /*
         删除待添加的商品
         */
        deleteCachedGoods: function (id) {
            var self = this;
            for (var i in self.goodsArray) {
                if (self.goodsArray[i].id == id) {
                    self.goodsArray.splice(i, 1);
                    break;
                }
            }
            self.refreshGoodsList();
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#goods_choose_func').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    goods_input: {
                        message: 'error',
                        validators: {
                            notEmpty: {
                                message: '店铺不得为空'
                            },
                            regexp: {
                                regexp: /^([0-9]+[,，])*[0-9]+$/,
                                message: '请输入店铺ID,英文逗号分隔'
                            }
                        }
                    }
                }
            });

        },
        /*
         提交
         */
        submit: function () {
            var self = this;
            var goods = new Array();
            //检查商品是否为空
            if (self.goodsArray.length <= 0) {
                CRM.showDialog("请添加商品");
                return;
            }
            //检查投放平台是否为空
            var platform_empty = true;
            self.ispArray = new Array();
            $("#platform input").each(function () {
                if ($(this).is(':checked')) {
                    platform_empty = false;
                    self.ispArray.push($(this).val());
                }
            });
            if (platform_empty) {
                CRM.showDialog("投放平台不得为空");
                return;
            }
            if (self.goodsArray.length <= 0) {
                CRM.showDialog("请添加商品");
                return;
            }
            $("#submit").attr("disabled", "disabled");
            //整理商品数组
            for (var i in self.goodsArray) {
                goods.push(self.goodsArray[i].id);
            }
            var dataString = {
                "actcatId": self.actcatId,
                "isp": self.ispArray.join(","),
                "spuIds": goods.join(","),
                "allShop": false,
                "timestamp": new Date().getTime()
            };
            if ($('input[value="全部店铺"]').is(':checked')) {
                dataString['allShop'] = true;
            } else if ($('input[value="手动输入店铺"]').is(':checked') || $('input[value="用Excel导入"]').is(':checked')) {
                dataString['allShop'] = false;
                $("#goods_choose_func").data('bootstrapValidator').validate();
                if ($("#goods_choose_func").data('bootstrapValidator').isValid()) {
                    re = new RegExp("，", "g");
                    dataString['shopIds'] = $('#goods_input').val().replace(re, ",");
                } else {
                    return;
                }
            }
            //console.log(dataString);
            $.ajax({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/actcat/create"),
                "dataType": "json",
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                "data": dataString,
                contentType: "application/json",
                "success": function (req) {
                    //console.log(req);
                    if (req.status) {
                        if (req.entry.length > 0) {
                            $('#failedGoods_table tbody').html("");
                            for (var i in req.entry) {
                                var html = '<tr><td>' + req.entry[i].shopId + '</td><td>' + req.entry[i].shopName + '</td><td>' + req.entry[i].spuId
                                    + '</td><td>' + req.entry[i].spuName + '</td><td>' + req.entry[i].message + '</td></tr>';
                                $('#failedGoods_table tbody').append(html);
                            }
                            $('#failedGoods_dialog').modal("show");
                        } else {
                            self.goodsArray = new Array();
                            self.cachedGoodsArray = new Array();
                            self.refreshGoodsList();
                            $("#goods_input").val("");
                            CRM.showDialog("所有商品已完成绑定该类目");
                        }
                    } else {
                        CRM.showDialog(req.message);
                    }
                    $("#submit").removeAttr("disabled", "disabled");
                },
                error: function (e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("请求服务异常！");
                    $('#msg_dialog').modal('show');
                    $("#submit").removeAttr("disabled", "disabled");
                }
            });

        },
        bindEvent: function () {
            var self = this;
            $("#goods_search_btn").on('click', function () {
                $('#goods_table').DataTable().ajax.reload();
            });
            $("#refresh").on('click', function () {
                window.location.href = "./addGoods.html?actcatId=" + self.actcatId + "&actcatName=" + self.actcatName + "&cityCode=" + self.cityCode;
            });
            $("#excel-download").on('click', function () {
                window.location.href = CRM.getOuterUrl("/outway/static/download/shop_ids.xlsx");
            });
            $('#addGoodsBtn').on('click', function () {
                self.cachedGoodsArray = new Array();
                $('#barcode_input').val('');
                $('#goods_table tbody').html("");
                $('#choosed_goods_list').html("");
                $('#goods_table_info').html("");
                $('#goods_table_paginate').html("");
                $('#chooseGoods_dialog').modal("show");
            });
            $('#submit').on('click', function () {
                self.submit();
            });
            //上传Excel文件
            $('#excel-upload-file').change(function () {
                var fileObj = document.getElementById("excel-upload-file").files[0]; // 获取文件对象
                var FileController = CRM.getOuterUrl("/outway/actcat/upload/shopIds");                    // 接收上传文件的后台地址
                // FormData 对象
                var form = new FormData();
                form.append("file", fileObj);                           // 文件对象
                // XMLHttpRequest 对象
                var xhr = new XMLHttpRequest();
                xhr.open("post", FileController, true);
                xhr.onloadstart = function () {
                    $('#excel-upload-btn').attr("disabled", "disabled");
                    $('#excel-upload-file').attr("disabled", "disabled");
                    $('#uploading').html("正在上传......0%");
                    $('#uploading').css("display", "inline");
                };
                xhr.onprogress = xhr.upload.onprogress = updateProgress;
                function updateProgress(event) {
                    if (event.lengthComputable) {
                        $('#uploading').html("正在上传......" + Math.round(event.loaded * 100 / event.total) + "%");
                    } else {
                        $('#uploading').html("上传成功");
                    }
                }

                xhr.onload = function () {
                    if (this.status == 200 || this.status == 304) {
                        var data = eval('(' + this.responseText + ')');
                        if (data.status) {
                            self.excelArray = new Array();
                            self.excelArray = data.entry;
                            $('#goods_input').val(self.excelArray.join(","));
                            $("#goods_choose_func").data('bootstrapValidator').resetForm();
                            $('#uploading').html("导入成功");
                        } else {
                            CRM.showDialog(data.message);
                        }
                    } else {
                        CRM.showDialog(this.responseText);
                    }
                    $('#excel-upload-file').val('');
                    $('#excel-upload-btn').removeAttr("disabled");
                    $('#excel-upload-file').removeAttr("disabled");
                };
                xhr.send(form);
            });
            $('input[name="identity"]').change(function () {
                //console.log($(this).val());
                if ($(this).val() == "手动输入店铺") {
                    $('#goods_choose_func').css("display", "block");
                    $('#input_area').css("display", "block");
                    $('#excel_func').css("display", "none");
                } else if ($(this).val() == "用Excel导入") {
                    $('#goods_choose_func').css("display", "block");
                    //$('#input_area').css("display", "none");
                    $('#excel_func').css("display", "block");
                } else {
                    $('#goods_choose_func').css("display", "none");
                }
            })
        }
    };
    window.cachedGoods = $.proxy(addGoods.cachedGoods, addGoods);
    window.chooseAll = $.proxy(addGoods.chooseAll, addGoods);
    window.showCachedGoods = $.proxy(addGoods.showCachedGoods, addGoods);
    window.deleteCachedGoods = $.proxy(addGoods.deleteCachedGoods, addGoods);
    addGoods.init();


});